package com.ks.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ks.entity.*;
import com.ks.service.*;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.ks.base.BaseAction;
import com.ks.util.HtmlUtil;


/**
 * <br>
 * <b>功能：</b>ExamCenterController<br>
 * <b>作者：</b>www.jeecg.org<br>
 * <b>日期：</b> Feb 2, 2013 <br>
 * <b>版权所有：<b>版权所有(C) 2013，www.jeecg.org<br>
 */
@Controller
@RequestMapping("/examCenter")
public class ExamCenterController extends BaseAction {

    private final static Logger log = Logger.getLogger(ExamCenterController.class);

    // Servrice start
    @Autowired(required = false) //自动注入，不需要生成set方法了，required=false表示没有实现类，也不会报错。
    private UserService<User> userService;
    @Autowired(required = false) //自动注入，不需要生成set方法了，required=false表示没有实现类，也不会报错。
    private ExamPaperService<ExamPaper> examPaperService;
    @Autowired(required = false) //自动注入，不需要生成set方法了，required=false表示没有实现类，也不会报错。
    private ExamPaperStudentService<ExamPaperStudent> examPaperStudentService;
    @Autowired(required = false) //自动注入，不需要生成set方法了，required=false表示没有实现类，也不会报错。
    private ExamineeService<Examinee> examineeService;
    @Autowired(required = false) //自动注入，不需要生成set方法了，required=false表示没有实现类，也不会报错。
    private ExamService<Exam> examService;
    /**
     * @param entity
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/list")
    public ModelAndView list(Depository entity, HttpServletRequest request) throws Exception {
        Map<String, Object> context = getRootMap();
        return forword("scott/exam/tKsDepository", context);
    }


    /**
     * 考生交卷算分
     *
     * @param entity
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/calculation")
    public ModelAndView calculation(ExamPaperStudent entity, HttpServletRequest request) {
        Map<String, Object> context = examPaperService.calculation(entity);
        return forword("/pages/examining/exam-results", context);
    }

    @RequestMapping("/examing")
    public ModelAndView examing(ExamPaper entity, HttpServletRequest request) {

        HttpSession session = request.getSession(true);
        String examid = request.getParameter("exam_id");
        entity.setExam_id(Integer.parseInt(examid));
        User user = (User) session.getAttribute("userInfo");
        Map<String, Object> context = examPaperService.examingPage(entity, user.getId());
        return forword("/pages/examining/exam", context);
    }

    @RequestMapping("/queryResultsPage")
    public ModelAndView queryResults(String examid, HttpServletRequest request) {
        Map<String, Object> context = new HashMap<>();
        context.put("examid", examid);
        return forword("pages/login_jfph", context);
    }

    @RequestMapping("/queryResultsDataList")
    public void queryResultsDataList(String examid, HttpServletRequest request, HttpServletResponse response) throws Exception{

        List<Examinee> list = examPaperService.queryResults(examid);
        for (Examinee examinee : list) {
            Integer user_id = examinee.getUser_id();
            User user = userService.queryById(user_id);
            examinee.setTest_number(user.getIdentityId());
        }
        HtmlUtil.writerJson(response, list);
    }

    @RequestMapping("/queryUserPaperResults")
    public ModelAndView queryUserPaperResults(HttpServletRequest request, HttpServletResponse response) {
        String examid = request.getParameter("examid");
        String paperid = request.getParameter("paperid");
        String studentid = request.getParameter("studentid");
        String studentName = request.getParameter("studentName");
        String score = request.getParameter("score");
        Map<String, Object> context = examPaperService.queryUserPaperResults(examid, paperid, studentid);
        context.put("studentName", studentName);
        context.put("score", score);
        return forword("/pages/examManagement/userExam", context);
    }

    /**
     * 考生的答题面板
     *
     * @param entity
     * @param response
     * @throws Exception
     */
    @RequestMapping("/answerDetail")
    public void answerDetail(HttpServletRequest request, HttpServletResponse response) {
        String exam_id = request.getParameter("exam_id");
        String paper_id = request.getParameter("paper_id");
        String user_id = request.getParameter("user_id");
        //设置页面数据
        Map<String, Object> jsonMap = new HashMap<>();
        Map<String, Object> map = new HashMap<>();
        map.put("exam_id",exam_id);
        map.put("paper_id",paper_id);
        map.put("user_id",user_id);
        //单选
        map.put("questiontype_id",1);
        List<Map<String, String>> singlelist = examPaperStudentService.queryPaperUserQuestions(map);
        //多选
        map.put("questiontype_id",2);
        List<Map<String, String>> mutilist = examPaperStudentService.queryPaperUserQuestions(map);
        //判断
        map.put("questiontype_id",3);
        List<Map<String, String>> judgelist = examPaperStudentService.queryPaperUserQuestions(map);
        jsonMap.put("singleans", singlelist);
        jsonMap.put("mutians", mutilist);
        jsonMap.put("judgeans", judgelist);
        HtmlUtil.writerJson(response, jsonMap);
    }

    /**
     * 添加或修改试题答案
     *
     * @param entity   ExamPaperStudentAnswer
     * @param response
     * @throws Exception
     */
    @RequestMapping("/answersAdd")
    @ResponseBody
    public void answersAdd(ExamPaperStudent entity, HttpServletResponse response) {
        if (null != entity.getAnswer() && !"".equals(entity.getAnswer())) {
            entity.setAnswer(entity.getAnswer());
        }
        examPaperStudentService.updateAnswersByQuestionid(entity);
        sendSuccessMessage(response, "保存成功~");
    }

    @RequestMapping("/getId")
    public void getId(String id, HttpServletResponse response) throws Exception {
        Map<String, Object> context = new HashMap<>();
        User entity = userService.queryById(id);
        if (entity == null) {
            sendFailureMessage(response, "没有找到对应的记录!");
            return;
        }
        context.put(SUCCESS, true);
        context.put("data", entity);
        HtmlUtil.writerJson(response, context);
    }
    @RequestMapping("/paperBoard")
    public void paperBoard(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String exam_id = request.getParameter("exam_id");
        String paper_id = request.getParameter("paper_id");
        String user_id = request.getParameter("user_id");
        //设置页面数据
        Map<String, Object> jsonMap = new HashMap<>();
        Map<String, Object> map = new HashMap<>();
        map.put("exam_id",exam_id);
        map.put("paper_id",paper_id);
        map.put("user_id",user_id);
        int questionleft = 0;
        double minuteslest = 0;
        List<Map<String, String>> singlelist = examPaperStudentService.queryPaperUserQuestions(map);
        for (Map<String, String> stringStringMap : singlelist) {
            if ("".equals(stringStringMap.get("answer"))) {
                questionleft = questionleft+1;
            }
        }
        List<Examinee> list = examineeService.queryList(map);
        long date = new Date().getTime();//当前时间
        long time = list.get(0).getStarttime().getTime();//考试时间
        Exam exam = examService.queryById(exam_id);
        long examTime = Long.parseLong(exam.getDuration());//考试时长 分钟
        // 开考前半小时
        minuteslest = examTime-(date-time)/60000;
        jsonMap.put("questionsleft",questionleft);
        jsonMap.put("minutesleft",minuteslest);
        HtmlUtil.writerJson(response, jsonMap);
    }
}
